/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2019年12月21日
*   版    本：v1.0.0
*   描    述：
*   Copyright (C) 2019 All rights reserved.
*   
* ================================================================*/


#include <iostream>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    int maxpath = 0;
public:
    int longestUnivaluePath(TreeNode* root) {
        getLongestUnivaluePath(root);
        return maxpath;
    }

    int getLongestUnivaluePath(TreeNode* root){
        if(!root)
            return 0;

        int left_path = getLongestUnivaluePath(root->left);
        int right_path = getLongestUnivaluePath(root->right);
        int ansleft = 0, ansright = 0;
        
        if(root->left && root->val == root->left->val){
            ansleft = left_path+1;
        }
        if(root->right && root->val == root->right->val){
            ansright = right_path+1;
        }

        maxpath = max(maxpath, ansleft+ansright);

        return max(ansleft, ansright);
    }
};